#include "home-dir.h"

#include <boost/process/environment.hpp>
#include "system-type.h"


static fs::path homeDirForWindows() {
    const boost::process::native_environment e = boost::this_process::environment();
    const auto driveIt = e.find("HOMEDRIVE");
    if (driveIt == e.end()) {
        throw os::EnvironmentForHomeDirNotFound("Environment 'HOMEDRIVE' not found");
    }
    const auto pathIt = e.find("HOMEPATH");
    if (pathIt == e.end()) {
        throw os::EnvironmentForHomeDirNotFound("Environment 'HOMEPATH' not found");
    }
    return fs::absolute(driveIt->to_string() + pathIt->to_string()).lexically_normal();
}

static fs::path homeDirForNotWindows() {
    const boost::process::native_environment e = boost::this_process::environment();
    const auto homeIt = e.find("HOME");
    if (homeIt == e.end()) {
        throw os::EnvironmentForHomeDirNotFound("Environment 'HOME' not found");
    }
    return fs::absolute(homeIt->to_string()).lexically_normal();
}


namespace os
{

const fs::path homeDir() {
#if defined(ABC_UTIL_SYSTEM_TYPE_IS_WINDOWS)
    return homeDirForWindows();
#else
    return homeDirForNotWindows();
#endif
}

} // namespace os
